package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Map;

public class EchoHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        try {
            Map<String, String> params = request.getAllParams();

            StringBuilder contentBuilder = new StringBuilder();
            contentBuilder.append("<!DOCTYPE html>\n")
                    .append("<html>\n")
                    .append("<head>\n")
                    .append("    <title>Echo Response</title>\n")
                    .append("    <style>\n")
                    .append("        body { font-family: Arial, sans-serif; margin: 40px; }\n")
                    .append("        h1 { color: #333; }\n")
                    .append("        h2 { color: #555; }\n")
                    .append("        ul { list-style-type: none; padding: 0; }\n")
                    .append("        li { background: #f8f9fa; margin: 5px 0; padding: 10px; border-left: 4px solid #007bff; }\n")
                    .append("        strong { color: #007bff; }\n")
                    .append("        .container { max-width: 800px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; }\n")
                    .append("        .request-info { background: #e9ecef; padding: 15px; border-radius: 5px; margin-bottom: 20px; }\n")
                    .append("        a { color: #007bff; text-decoration: none; }\n")
                    .append("        a:hover { text-decoration: underline; }\n")
                    .append("    </style>\n")
                    .append("</head>\n")
                    .append("<body>\n")
                    .append("    <div class=\"container\">\n")
                    .append("        <h1>Echo Server Response</h1>\n")
                    .append("        <div class=\"request-info\">\n")
                    .append("            <h2>Request Details:</h2>\n")
                    .append("            <p><strong>Method:</strong> ").append(escapeHtml(request.getMethod())).append("</p>\n")
                    .append("            <p><strong>URL:</strong> ").append(escapeHtml(request.getUrl())).append("</p>\n")
                    .append("        </div>\n");

            // 根据接收到的参数Map构建HTML列表，回显给客户端
            if (params.isEmpty()) {
                contentBuilder.append("        <h2>No Parameters Received.</h2>\n");
                contentBuilder.append("        <p>Try adding parameters to the URL, for example: <code>/echo?name=John&age=25</code></p>\n");
            } else {
                contentBuilder.append("        <h2>Received Parameters:</h2>\n")
                        .append("        <ul>\n");

                for (Map.Entry<String, String> entry : params.entrySet()) {
                    contentBuilder.append("            <li><strong>")
                            .append(escapeHtml(entry.getKey()))
                            .append("</strong>: ")
                            .append(escapeHtml(entry.getValue()))
                            .append("</li>\n");
                }

                contentBuilder.append("        </ul>\n");
            }

            contentBuilder.append("        <p><a href=\"/\">← Back to Home</a></p>\n")
                    .append("    </div>\n")
                    .append("</body>\n")
                    .append("</html>");

            String content = contentBuilder.toString();
            byte[] contentBytes = content.getBytes("UTF-8");

            // 构造完整的 HTTP 响应头
            StringBuilder header = new StringBuilder();
            header.append("HTTP/1.1 200 OK\r\n");
            header.append("Content-Type: text/html; charset=UTF-8\r\n");
            header.append("Content-Length: ").append(contentBytes.length).append("\r\n");
            header.append("Connection: close\r\n");
            header.append("\r\n");  // 空行分隔头部和正文

            // 先写入头部
            response.write(header.toString().getBytes("UTF-8"));
            // 再写入内容
            response.write(contentBytes);
            response.flush();

        } catch (IOException e) {
            System.err.println("Error in EchoHandler: " + e.getMessage());
            try {
                // 发生错误时返回500
                String errorContent = "<h1>500 Internal Server Error</h1><p>Error generating echo response</p>";
                byte[] errorBytes = errorContent.getBytes("UTF-8");

                String errorHeader = "HTTP/1.1 500 Internal Server Error\r\n" +
                        "Content-Type: text/html; charset=UTF-8\r\n" +
                        "Content-Length: " + errorBytes.length + "\r\n" +
                        "Connection: close\r\n\r\n";

                response.write(errorHeader.getBytes("UTF-8"));
                response.write(errorBytes);
                response.flush();
            } catch (IOException ex) {
                System.err.println("Failed to send error response: " + ex.getMessage());
            }
        }
    }

    /**
     * 辅助方法：对HTML特殊字符进行转义，防止XSS攻击
     */
    private String escapeHtml(String text) {
        if (text == null) return "";
        return text.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#39;");
    }
}